package com.example.project01.api;

import com.aliyun.oss.OSS;
import com.example.project01.model.Feedback;
import com.example.project01.service.FeedbackService;
import com.leon.model.I18nException;
import com.leon.web.annotation.ApiAuth;
import com.leon.web.annotation.ApiLogger;
import com.leon.web.annotation.ApiSetting;
import com.leon.web.annotation.Condition;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.Objects;


@Slf4j
@Validated
@RestController
@AllArgsConstructor
@RequestMapping("/app")
public class AppFeedbackApi {

    private final FeedbackService feedbackService;
    private final OSS oss;

    @Operation(description = "存储用户feedback")
    @PostMapping(value = "/feedback", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiSetting(log = @ApiLogger(print = true), auth = @ApiAuth(condition = Condition.SESSION))
    public ResponseEntity<?> newFeedback(@Valid @RequestBody Feedback feedback, @RequestPart("file") MultipartFile file) throws I18nException {
        try(var inputStream = new ByteArrayInputStream(file.getBytes())) {
            var ossPathname = "feedback/" + feedback.getLiaison() + ".jpg";
            this.oss.putObject("feedback-image", ossPathname, inputStream);
            String url = file.getOriginalFilename() + "https://t2a-mvno.oss-cn-shanghai.aliyuncs.com/" + ossPathname;
            feedback.setImage(url);
        } catch (Exception e) {
            BannerApi.Uploaded uploaded = BannerApi.Uploaded.empty();
            log.error(e.getMessage(), e);
            return ResponseEntity.ok().body(uploaded);
        }
        if (Objects.isNull(feedback.getLiaison())) {
            throw new I18nException("feedback.liaison.error");
        }
        int result = feedbackService.save(feedback, false);
        if (result <= 0){
            throw new I18nException("feedback.error");
        }
        return ResponseEntity.ok().build();
    }

}
